<template>
  <div class="app-container">
    <!-- 条件栏 -->
    <NewPageFilter
      v-model:query="filterInfo.query.queryMap"
      :query-more-json="true"
      :filter-list="filterInfo.searchList"
      :filter-btn="filterInfo.searchBtn"
      :list-type-info="listTypeInfo"
      :slip-select-request="slipSelectRequest"
      :clear-type="clearType"
    >
    <template v-slot:filter-useDeptName>
            <slip-select
              v-model="filterInfo.query.queryParams.useDeptIdMult"
              value-key="value"
              placeholder="选择使用部门"
              :api="inOrOutDepotInfo.api"
              key-field="name"
              value-field="id"
              v-model:query="inOrOutDepotInfo.query"
              :clearable="true"
              :filterable="true"
              :multiple="true"
              @change="search"
            />
          </template>
    </NewPageFilter>
    <div class="filter-wrapper">
      <NewPageFilter :filter-btn="filterInfo.btnList">
        <template v-slot:filter-print>
          <PopoverPrint
            ref="popoverShow"
            v-model:popoverVisible="popoverVisible"
            :canPrint="true"
            :templateArr="templateArr"
            @tempClick="tempClick"
            @print="print"
          ></PopoverPrint>
        </template>
      </NewPageFilter>
      <div class="display-flex">
        <el-button @click="preferenceInfo.visible = true">偏好设置</el-button>
      </div>
    </div>

    <!-- 表格 -->
    <TableContainer
      :refresh="tableInfo.refresh"
      :init-curpage="tableInfo.initCurpage"
      v-model:data="tableInfo.data"
      :api="tableInfo.api"
      :summary="false"
      :allSummary="false"
      :tab-index="true"
      :check-box="false"
      :query="filterInfo.query"
      :field-list="tableInfo.fieldList"
      @sortChange="sortChange"
      @handleEvent="handleEvent"
      @pageInfo="pageInfo"
    >
      <template v-slot:col-assetName="scope">
          {{ scope.row.assetName }}
        </template>
    </TableContainer>

    <PageDialog
      v-if="dialogInfo.visible"
      :title="dialogInfo.title"
      v-model:visible="dialogInfo.visible"
      :width="dialogInfo.width"
      :bt-loading="dialogInfo.btLoading"
      :bt-list="dialogInfo.btList"
    >
      <div class="asset-msg">
        <div class="asset-msg-label">
          <i class="el-icon-warning"></i>{{ dialogInfo.msg }}：
        </div>
        <el-radio-group v-model="dialogInfo.flag">
          <el-radio :label="true">当前页数据</el-radio>
          <el-radio :label="false">全部页数据</el-radio>
        </el-radio-group>
      </div>
    </PageDialog>
    <set-preference
      v-if="preferenceInfo.visible"
      v-model:visible="preferenceInfo.visible"
      :search-list="filterInfo.searchList"
      :field-list="tableInfo.fieldList"
      :customize-user-v-o="filterInfo.query.customizeUserVO"
      :group-level-show="false"
      @callback="setPreferenceCallback"
    />
  </div>
</template>

<script setup name="lifeSupportAsset">
import { selectByCodeAndDept } from "@/api/report.js";
import { doPrint } from "@/utils/exportUtil.js";

import { getCustomizeSetting, updateUserCustomize } from "@/api/customize";
import { getAssetCardCustomizePage, getDeptAll, exportAssetCard  } from "@/api/core";

const { proxy } = getCurrentInstance();
const clearType = ref(true);
const popoverVisible = ref(false);
const slipSelectRequest = ref(true)
const templateArr = ref([]);

const preferenceInfo = ref({
  visible: false,
});
const listTypeInfo = ref({
  depotList: [],
  supplierList: [],
});

const filterInfo = ref({
  sortArr: [],
  query: {
    sortString: "",
    customizeUserVO: {},
    queryMap: {
      id: {
        queryType: 'IN',
        queryCategory: 'AND',
        value: '',
      },
      assetStatus: {
        queryType: 'IN',
        value: '1,3',
      },
      status: {
        queryType: 'IN',
        value: '3',
      },
      assetMark: {
        queryType: 'ALL_LIKE',
        queryCategory: 'AND',
        value: '4',
      },
    },
    copyQueryMap: {},
    queryParams: {},
  },
  searchList: [],
  searchBtn: [
    { type: "button", label: "搜索", event: search },
    { type: "button", label: "重置", event: clearSearch },
  ],
  btnList: [
    {
      type: "slot",
      value: "print",
      show: proxy.$permission("lifeSupportAsset:print"),
    },
    {
      type: "button",
      label: "导出excel",
      event: exportExcel,
      show: proxy.$permission("lifeSupportAsset:excel"),
    },
  ],
});
const inOrOutDepotInfo = reactive({
  api: getDeptAll,
  query: {
    deptAuth: 'id',
    status: 1,
  },
})
const tableInfo = ref({
  refresh: 1,
  initCurpage: 1,
  data: [],
  api: undefined,
  selections: [],
  fieldList: [],
  handle: {
    fixed: "right",
    label: "操作",
    width: "100",
    btList: [],
  },
});
const dialogInfo = ref({
  visible: false,
  title: "提示",
  btLoading: false,
  type: "",
  msg: "",
  width: "400px",
  flag: true,
  btList: [
    { label: "关闭", event: handleClose, show: true },
    {
      label: "打印",
      type: "primary",
      event: checkConfirm,
      show: true,
    },
  ],
});

const page = ref({
  curPage: 1, // 当前页
  pageSize: 20, // 每页条数
});

function handleEvent(event, data) {
  switch (event) {
    case "tableCheck":
      tableInfo.value.selections = [...data];
      break;
  }
}

function setPreferenceCallback(obj) {
  updateUserCustomize(obj.customizeUserVO).then((res) => {
    if (res && res.success) {
      getCustomize(!slipSelectRequest.value);
    }
  });
}
let obj = {
  supplierName: {
    label: '供应商',
    value: 'supplierName',
    componentType: 'input',
    show: false,
    hidden: true,
  },
  assetName: {
    label: '资产名称',
    value: 'assetName',
    componentType: 'input',
    show: false,
    type: 'slot',
    hidden: true,
  },
  statusValue: {
    label: '状态',
    value: 'statusValue',
    asValue: 'status',
    componentType: 'select-model',
    code: 'asset_register_status',
    show: false,
    hidden: true,
  },
  repairStatusValue: {
    label: '设备状态',
    value: 'repairStatusValue',
    asValue: 'repairStatus',
    componentType: 'select-model',
    code: 'asset_repair_status',
    show: false,
    hidden: true,
  },
  assetTypeValue: {
    label: '资产类型',
    value: 'assetTypeValue',
    asValue: 'assetType',
    componentType: 'select-model',
    code: 'asset_type',
    show: false,
    hidden: true,
  },
  increaseTypeValue: {
    label: '增加方式',
    value: 'increaseTypeValue',
    asValue: 'increaseType',
    componentType: 'select-model',
    code: 'increase_type',
    show: false,
    hidden: true,
  },
  deprConventionValue: {
    label: '折旧惯例',
    value: 'deprConventionValue',
    asValue: 'deprConvention',
    componentType: 'select-model',
    code: 'depr_convention',
    show: false,
    hidden: true,
  },
  deprMethodTypeValue: {
    label: '折旧方法',
    value: 'deprMethodTypeValue',
    asValue: 'deprMethodType',
    componentType: 'select-model',
    code: 'depr_method_type',
    show: false,
    hidden: true,
  },
  isLockedValue: {
    label: '是否锁定',
    value: 'isLockedValue',
    asValue: 'isLocked',
    componentType: 'select-model',
    code: 'is_locked',
    show: false,
    hidden: true,
  },
  // assetStatusValue: {
  //   label: '资产状态',
  //   value: 'assetStatusValue',
  //   asValue: 'assetStatus',
  //   componentType: 'select-model',
  //   code: 'asset_status',
  //   show: false,
  //   hidden: true,
  // },
  useDeptName: {
    label: '使用部门',
    value: 'useDeptName',
    asValue: 'useDeptId',
    query: {
      deptAuth: 'id',
      status: 1,
    },
    api: getDeptAll,
    componentType: 'slip-select',
    show: false,
    hidden: true,
  },
}
tableInfo.value.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
filterInfo.value.searchList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...proxy.$fn.deepClone(obj),
})
getCustomize()

function getCustomize(slipSelect = true) {
  let param = {
    tableKey: 'assetEmergencyLifeSupportList-com.slip.spd.entity.vo.core.CoreAssetVO',
  }
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data
      filterInfo.value.query.customizeUserVO = data
      let searchInfo = proxy.$fn.setSearchList(
        filterInfo.value.searchList,
        data.detail
      )
      let tableFieldInfo = proxy.$fn.setFieldList(
        tableInfo.value.fieldList,
        data.detail,
        true
      )

      tableInfo.value.fieldList = tableFieldInfo.fieldList
      filterInfo.value.query.queryMap = {
        ...searchInfo.queryMap,
        ...filterInfo.value.query.queryMap,
      }
      filterInfo.value.copyQueryMap = proxy.$fn.deepClone(
        filterInfo.value.query.queryMap
      )
      filterInfo.value.searchList = [
        ...searchInfo.searchList,
        {
          slot: true,
          value: 'useDeptName',
        },
      ]
      filterInfo.value.searchList.forEach((item) => {
        item.event = search
      })
      slipSelectRequest.value = slipSelect
      tableInfo.value.api = getAssetCardCustomizePage
      getList()
    }
  })
}
function sortChange(column) {
  if (filterInfo.value.query.customizeUserVO.head.sortType === 0) {
    let arr = proxy.$fn.sortChange(column, filterInfo.value.sortArr)
    filterInfo.value.sortArr = arr
    filterInfo.value.query.sortString = arr.length ? arr.toString() : ''
    getList()
  }
}
function getList() {
  tableInfo.value.refresh = Math.random();
}
function search() {
  tableInfo.value.initCurpage = Math.random();
  tableInfo.value.refresh = Math.random();
}
function clearSearch() {
  clearType.value = !clearType.value;
  filterInfo.value.query.queryMap = proxy.$fn.deepClone(
    filterInfo.value.copyQueryMap
  );
  filterInfo.value.query.queryParams.useDeptIdMult = ''
  search();
}

function handleClose() {
  dialogInfo.value.visible = false;
}
function print() {
    //打印
  dialogInfo.value.flag = true
  dialogInfo.value.visible = true
  dialogInfo.value.type = 'print'
  dialogInfo.value.msg = '请选择当数据打印范围'
  dialogInfo.value.btList[1].label = '打印'
 
}
function tempClick(item) {
  doPrint({
    name: item.ureportName,
    params: {
      ...filterInfo.value.query,
    },
    callback: printCallback,
    data: {},
  });
  popoverVisible.value = false;
}

function printCallback() {
  try {
    // 打印成功增加打印次数
    // updatePrintCount({
    //   orderNo: infoList.value.data.orderNo,
    //   orderId: props.orderId,
    //   tempCode: 'paymentDeatil',
    //   orderType: 0,
    // })
  } catch (error) {}
}

//打印导出
function pageInfo(obj) {
  page.value = obj;
}
function exportExcel() {
  //导出
  dialogInfo.value.visible = true;
  dialogInfo.value.type = "excel";
  dialogInfo.value.msg = "请选择数据导出范围";
  dialogInfo.value.btList[1].label = "导出";
  dialogInfo.value.flag = true;
}
function checkConfirm() {
  if (dialogInfo.value.type === "excel") {
    exportExcelList();
    } else if (dialogInfo.value.type === 'print') {
    printList()
  }
  dialogInfo.value.visible = false;
  dialogInfo.value.msg = "";
}

function printList() {
   selectByCodeAndDept({
    tempCode: "assetEmergencyLifeSupportList",
  }).then((res) => {
    if (res && res.success) {
      templateArr.value = res.data;
      popoverVisible.value = true;
      // 一条数据则直接打印
      if (templateArr.value.length === 1) {
        console.log(proxy.$refs.popoverShow);
        proxy.$refs.popoverShow.hidePopover();
        doPrint({
          name: templateArr.value[0].ureportName,
          params: {},
          callback: printCallback,
          data: {
            customParam: JSON.stringify({
              ...filterInfo.value.query,
              ...page.value,
              page: dialogInfo.value.flag
            }),
          },
        });
      }
    }
  });
}

function exportExcelList() {
  filterInfo.value.query.queryMap.id.value = ''
  if (dialogInfo.value.flag === 'select') {
    if (!tableInfo.value.selections.length) {
      proxy.$message.warning({
        message: '请选择数据！',
        showClose: true,
        duration: 3000,
      })
      return
    }
    let ids = tableInfo.value.selections.map((item) => item.id).join(',')
    filterInfo.value.query.queryMap.id.value = ids
  }
  let params = {
    ...filterInfo.value.query,
    ...page.value,
    page: dialogInfo.value.flag,
    queryParams:{
      isEmergencyLifeSupportQuery: true
    }
  }

  exportAssetCard(params).then((resp) => {
    if (resp) {
      proxy.$fn.parseExcel(resp)
    }
  })
}
</script>

<style scoped></style>
